package controllers

import (
	"devOpsApi/base"
	"devOpsApi/common/util"
	"devOpsApi/config/ymlgo"
	"devOpsApi/libs"
	"github.com/kataras/iris"
	"io/ioutil"
	"os"
)

type SettingController struct {
	base.BController
}

func (c *SettingController) GetTestEmail() {
	testEmail := c.Ctx.URLParamDefault("email", "")
	if testEmail == "" {
		c.OutDataJson("", iris.StatusBadRequest, "testEmail is empty ")
		return
	}
	//,"./uploads/PipelineLogs/52/12213213_1337.log"
	err := libs.SendEmail(testEmail, "test email ", "this is a demo")
	if err != nil {
		c.OutDataJson("", iris.StatusBadRequest, err.Error())
		return
	}
	c.OutDataJson("", iris.StatusOK, "success")
}

func (c *SettingController) GetEmail() {
	ConfigEmail := ymlgo.NewConfigEmail()
	c.OutDataJson(ConfigEmail, iris.StatusOK, "success")
}

func (c *SettingController) PostEmail() {
	ConfigEmail := ymlgo.NewConfigEmail()
	err := ConfigEmail.Update(c.Ctx)
	if err != nil {
		c.OutDataJson("", iris.StatusBadRequest, err.Error())
		return
	}
	c.OutDataJson(ymlgo.NewConfigEmail(), iris.StatusOK, "success")
}

func (c *SettingController) GetPublicSshKey() {
	HomeDir, _ := os.UserHomeDir()
	idRsaFile := HomeDir + "/.ssh/id_rsa.pub"
	if exist := util.FileExists(idRsaFile); exist == false {
		c.OutDataJson("服务器"+HomeDir+"/.ssh/id_rsa.pub 公钥不存在,请联系管理员使用以下命令生成\nssh-keygen -t rsa -C \"xxxxx@xxxxx.com\"", iris.StatusOK, "success")
		return
	}
	idRsa, err := ioutil.ReadFile(idRsaFile)
	if err != nil {
		c.OutDataJson("读取公钥失败："+err.Error(), iris.StatusOK, "success")
		return
	}
	outStr := (string(idRsa)) + "\n将上面公钥添加至主机&nbsp;&nbsp;/【主机账号】/.ssh/authorized_keys文件里"
	c.OutDataJson(outStr, iris.StatusOK, "success")
}
